import {observable, action, toJS} from 'mobx';
import {WeaTableNew, WeaForm} from 'comsMobx';
import {WeaLocaleProvider} from "ecCom";
import {message, Modal} from "antd";
import _ from 'lodash';
import * as contractManagementApi from '../api/ContractManagementApi';
import CommonConfig from '../constant/CommonConfig';
import {indexOf, isBlank, parseIntValue} from '../util/CommonUtil';
import LanguageConstant from '../constant/LanguageConstant';


const confirm = Modal.confirm
const {TableStore} = WeaTableNew;
const {getLabel} = WeaLocaleProvider;

class ImportMouldStore {

    /**
     * 是否有操作页面的权限
     *
     * @type {boolean}
     */
    @observable authorized = true;

    /**
     * 加载状态
     */
    @observable loading = false;

    /**
     * 导入模板文件列表数据
     *
     * @type {{columns: Array, datas: Array}}
     */
    @observable importedMouldFiles = [];

    /**
     * 导入模板文件的id
     */
    @observable importedFileIds = [];

    /**
     * 导入模板列表删除按钮
     */
    @observable deleteButtonDisabled = false;

    /**
     * 选择框选择的数据
     */
    @observable selectedRowKeys = [];

    /**
     * 已被删除的模板文件id
     */
    @observable deletedImportedFileIds = [];

    /**
     * 模板文件上传最大值
     *
     * @type {number}
     */
    @observable maxMouldFileUploadSize = 10;

    /**
     * 默认模板类型
     *
     * @type {number}
     */
    defaultType = -1;

    /**
     * 模板类型下拉选择框
     *
     * @type {Array}
     */
    typeOptions = [];

    /**
     * 选择的分部
     *
     * @type {number}
     */
    selectedSubCompanyId = -1;

    @observable subcompany = undefined;

    /**
     * 开启分权管理
     */
    @observable detachedMaintenance = false;

    /**
     * 所属机构是否可编辑
     *
     * @type {boolean}
     */
    @observable subCompanyEditable = false;

    /**
     * 导入模板组件重置相关数据
     */
    @action
    resetImportMouldComponent = () => {
        this.importedFileIds = [];
        this.importedMouldFiles = [];
        this.typeOptions = [];
        this.deletedImportedFileIds = [];
        this.defaultType = -1;
        this.selectedSubCompanyId = -1;
        this.subCompanyEditable = false;
        this.subcompany = undefined;
    }

    /**
     * 初始化
     *
     * @param params
     */
    init = (params = {}) => {
        const {defaultType, selectedSubCompanyId} = params;
        this.defaultType = defaultType;
        this.selectedSubCompanyId = selectedSubCompanyId;
        this.loading = true;
        contractManagementApi.getImportMouldForm(params).then(res => {
            const {code, data} = res;
            this.loading = false;
            if (code == 200) {
                const {maxMouldFileUploadSize, detachedMaintenance, subCompanyEditable, subcompany} = data;
                this.detachedMaintenance = detachedMaintenance;
                this.subCompanyEditable = subCompanyEditable;
                this.subcompany = subcompany;
                this.maxMouldFileUploadSize = maxMouldFileUploadSize ? maxMouldFileUploadSize : CommonConfig.maxMouldFileUploadSize;
            } else {
                this.resetImportMouldComponent();
                message.error(getLabel("518561", "操作失败"));
            }
        });
    }

    /**
     * 获取导入模板文件列表数据
     * @param params
     */
    @action
    getImportedMouldFileTable = () => {
        const fileIds = toJS(this.importedFileIds).join(",");
        const defaultType = toJS(this.defaultType);
        const params = {fileIds, defaultType};
        this.loading = true;
        contractManagementApi.getImportedMouldFileTable(params).then(res => {
            const {code, data} = res;
            this.loading = false;
            if (code == 200) {
                const {mouldFiles, selectOptions} = data;
                if (selectOptions && selectOptions.type) {
                    this.typeOptions = selectOptions.type;
                }
                this.importedMouldFiles = mouldFiles;
            } else {
                this.resetImportMouldComponent();
                message.error(getLabel("518561", "操作失败"));
            }
        });
    }

    /**
     * 附件上传完成事件处理
     *
     * @param ids
     * @param list
     */
    @action
    onFileUploadChange = (ids, list) => {
        const deletedImportedFileIds = toJS(this.deletedImportedFileIds);
        // 先去除已删除的数据
        this.importedFileIds = _.difference(ids, deletedImportedFileIds);
        this.getImportedMouldFileTable();
    }


    @action
    onUploading = (status) => {
        const loading = toJS(this.loading);
        if (status == 'uploading' && !loading) {
            this.loading = true;
        } else if (status != 'uploading') {
            this.loading = false;
        }
    }

    /**
     * 分部浏览按钮修改
     */
    onSubcompanyChange = (ids, names, datas) => {
        this.selectedSubCompanyId = ids;
        this.subcompany = datas[0];
    }

    /**
     * 删除上传的文件
     *
     * @param datas
     * @param keys
     */
    @action
    affirmDelete = (datas, keys) => {
        confirm({
            title: getLabel('518566', "信息确认"),
            content: getLabel('518567', "确定要删除吗？"),
            okText: getLabel('518568', "是"),
            cancelText: getLabel('518569', "否"),
            onOk: () => this.deleteImportedFiles(keys),
            onCancel() {
            },
        });
    }

    /**
     * 删除已上传的模板文件
     *
     * @param keys
     */
    @action
    deleteImportedFiles = (keys) => {
        const importedFileIds = toJS(this.importedFileIds);
        for (let i = 0; i < keys.length; i++) {
            let index = indexOf(importedFileIds, keys[i]);
            if (index > -1) {
                importedFileIds.splice(index, 1);
            }
        }
        // 记录被删除的数据
        const deletedImportedFileIds = toJS(this.deletedImportedFileIds);
        keys.map(item => {
            deletedImportedFileIds.push(item);
        })
        this.deletedImportedFileIds = deletedImportedFileIds;
        this.importedFileIds = importedFileIds;
        this.getImportedMouldFileTable();
    }

    /**
     * 选择行
     *
     * @param selectedRowKeys
     */
    @action
    onRowSelect = selectedRowKeys => {
        const deletedImportedFileIds = toJS(this.deletedImportedFileIds);
        _.remove(selectedRowKeys, (e) => {
            return deletedImportedFileIds.indexOf(e) != -1;
        });
        this.selectedRowKeys = selectedRowKeys;
    }

    /**
     * 更新
     * @param fileId
     * @param dataIndex
     * @param value
     * @param record
     */
    @action
    onChangeField = (fileId, dataIndex, value, record) => {
        const importedMouldFiles = toJS(this.importedMouldFiles);
        if (!_.isArray(importedMouldFiles)) {
            return;
        }
        for (let i = 0; i < importedMouldFiles.length; i++) {
            let importedFile = importedMouldFiles[i];
            if (importedFile && value !== undefined && value !== null && importedFile.fileId == fileId) {
                importedFile[dataIndex] = value;
            }
        }
        this.importedMouldFiles = importedMouldFiles;
    }

    /**
     * 保存上传模板文件
     */
    @action
    saveMouldFiles = (closeDialogCallback) => {
        this.addMouldFiles(closeDialogCallback);
    }

    /**
     * 校验必填数据
     */
    checkMustInput = () => {
        const importedMouldFiles = toJS(this.importedMouldFiles);
        for (let i = 0; i < importedMouldFiles.length; i++) {
            let item = importedMouldFiles[i];
            if (item != undefined) {
                if (isBlank(item.name) || parseIntValue(item.type, -1) <= 0) {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 保存上传模板文件
     */
    @action
    addMouldFiles = (closeDialogCallback) => {
        if (!this.checkMustInput()) {
            message.error(getLabel(LanguageConstant.PLEASE_FILL_MUSTINPUT_FIELD, "请填写必填内容"));
            return;
        }
        this.loading = true;
        const importedMouldFiles = JSON.stringify(toJS(this.importedMouldFiles));
        const method = "add";
        const selectedSubCompanyId = toJS(this.selectedSubCompanyId);
        contractManagementApi.addMould({importedMouldFiles, method, selectedSubCompanyId}).then(res => {
            this.loading = false;
            const {code} = res;
            this.resetImportMouldComponent();
            if (code == 200) {
                message.success(getLabel("518560", "操作成功"));
            } else {
                message.error(getLabel("518561", "操作失败"));
            }
            if (closeDialogCallback && _.isFunction(closeDialogCallback)) {
                closeDialogCallback();
            }
        });
    }

}

export default ImportMouldStore;